import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/vuex/store'

Vue.use(Router)

export const constantRouterMap = [
  { path: '/install', component: () => import('@/views/install/index'), hidden: true },
  { path: '/login', component: () => import('@/views/login/index'), hidden: true },
  { path: '/register', component: () => import('@/views/login/register'), hidden: true },
  { path: '/map', component: () => import('@/views/map/index'), hidden: true },
  { path: '/404', component: () => import('@/views/404'), hidden: true }
]

if (localStorage.user) {
  store.dispatch('initCommonData').then(data => {
    router.addRoutes(data)
  })
}


const router = new Router({
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
})

// 不重定向白名单
const whiteList = ['/login','/register','/install']


router.beforeEach((to, from, next) => {

  NProgress.start()

  if (to.query.hasOwnProperty('root') && to.query.root === 'ypt') {
    next()
    NProgress.done()
  } else {
    if (localStorage.user) {
      if (to.path === '/login') {
        next({ path: '/' })
      }else {
        next()
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next('/login')
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
